import { dayjs } from 'element-plus'
import type { App, Plugin } from 'vue'

export const withInstall = <T>(component: T, alias?: string) => {
  const comp = component as any
  comp.install = (app: App) => {
    app.component(comp.name || comp.displayName, comp)
    if (alias) {
      app.config.globalProperties[alias] = component
    }
  }
  return component as T & Plugin
}

/** 白屏时间 */
export const blankTime = () => {
  const t: any = performance.getEntriesByType('navigation')[0]
  const value = (t?.domInteractive ?? t?.domLoading ?? 0) - t?.fetchStart
  return `${value.toLocaleString()}ms`
}

/**
 * 时间戳转日期时间
 * @param {number} date 时间戳
 * @param {string} template 转换格式
 * @returns
 */
export const formatUnix = (
  date: number,
  template: string = 'YYYY-MM-DD HH:mm:ss'
): string => {
  return date ? dayjs.unix(date).format(template) : '-'
}
//断任意日期是否过期
export const isExpired = (date: number) => {
  const now = dayjs() // 当前时间
  const expirationDate = dayjs(date) // 过期时间
  return now.isAfter(expirationDate)
}
/**
 * 获取静态资源
 * @param path 相对于assets的资源路径
 * @returns
 */
export const getAssetsUrl = (path: string) => {
  return new URL(`../assets/${path}`, import.meta.url).href
}
//根据传入的url判断是否存在htt或https
export const isHttpOrHttps = url => {
  const reg = /(http|https):\/\/([\w.]+\/?)\S*/
  return reg.test(url)
}

export const baseUrl = computed(() => {
  const appStore = useAppStore()
  if (import.meta.env.VITE_ENABLE_EXTERNAL_CONFIG === 'yes') {
    if (isHttpOrHttps(appStore.request_api) || appStore.request_api !== '/') {
      return appStore.request_api
    }
    return window.location.origin
  } else {
    return import.meta.env.VITE_BASE_URL
  }
})
//图片拼接
export const convertFileUrl = (relativeUrl: string) => {
  return baseUrl.value + relativeUrl
}
